package cn.edu.xmu.restfuldemo.controller;

import cn.edu.xmu.restfuldemo.model.OrdersVo;
import cn.edu.xmu.restfuldemo.model.VoObject;
import cn.edu.xmu.restfuldemo.service.OrderService;
import cn.edu.xmu.restfuldemo.util.ReturnObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

import static cn.edu.xmu.restfuldemo.util.Common.getRetObject;
import static cn.edu.xmu.restfuldemo.util.Common.processFieldErrors;

@RestController
@RequestMapping(value = "/orders", produces = "application/json;charset=UTF-8")
public class OrdersController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private HttpServletResponse httpServletResponse;


    @GetMapping("/{id}")
    public Object findOrderById(@PathVariable("id") Integer id) {
        ReturnObject<VoObject> returnObject = orderService.findById(id);
        return getRetObject(returnObject);
    }

    @PostMapping("/")
    public Object createOrder(@Validated @RequestBody OrdersVo orderVo, BindingResult bindingResult){
        Object returnObject = processFieldErrors(bindingResult, httpServletResponse);
        if (null != returnObject){
            return returnObject;
        }
        ReturnObject<VoObject> returnObject1 = orderService.create(orderVo);
        httpServletResponse.setStatus(HttpStatus.CREATED.value());
        return getRetObject(returnObject1);
    }


}
